﻿using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using Cef.Utility.Helper;
using CefSharp.MinimalExample.WinForms.Controls;
using CefSharp.MinimalExample.WinForms.Handler;
using CefSharp.WinForms;
using NLog;
using Spire.Pdf;

namespace CefSharp.MinimalExample.WinForms
{
    public partial class StarupForm : Form
    {
        private readonly ChromiumWebBrowser _browser;
        private readonly Logger _logger;
        PrintDocument printDocument;
        public StarupForm()
        {
            InitializeComponent();

            _logger = LogManager.GetCurrentClassLogger();
            _logger.Info("Init");
            this.KeyPreview = true;
            //初始化窗口大小为最大化
            MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
            WindowState = FormWindowState.Maximized;
            //隐藏高级功能
            var env = ConfigurationManager.AppSettings["Env"];
            if (!env.ToLower().Equals("debug"))
            {
                MenuHide();
            }
            
            //初始化浏览窗口内容
            var startupUrl = ConfigurationManager.AppSettings["StartupUrl"];
            if (string.IsNullOrEmpty(startupUrl))
            {
                MessageBox.Show("系统地址未配置，请联系管理员");
                Close();
            }
            _browser = new ChromiumWebBrowser(startupUrl)
            {
                KeyboardHandler = new KeyboardHandler(),
                Dock = DockStyle.Fill,
            };
            var boundObj = new BoundObject();
            _browser.RegisterJsObject("dotNet", boundObj);
            //_browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject());

            //toolStripContainer.ContentPanel.Controls.Add(_browser);
            this.BowserView.Controls.Add(_browser);
            _browser.LoadingStateChanged += OnLoadingStateChanged;
            _browser.ConsoleMessage += OnBrowserConsoleMessage;
            _browser.StatusMessage += OnBrowserStatusMessage;
            _browser.TitleChanged += OnBrowserTitleChanged;
            _browser.AddressChanged += OnBrowserAddressChanged;

            var bitness = Environment.Is64BitProcess ? "x64" : "x86";
            var version = $"Chromium: {Cef.ChromiumVersion}, CEF: {Cef.CefVersion}, CefSharp: {Cef.CefSharpVersion}, Environment: {bitness}";
            DisplayOutput(version);
            
        }

        private void OnBrowserConsoleMessage(object sender, ConsoleMessageEventArgs args)
        {
            DisplayOutput(string.Format("Line: {0}, Source: {1}, Message: {2}", args.Line, args.Source, args.Message));
        }

        private void OnBrowserStatusMessage(object sender, StatusMessageEventArgs args)
        {
            //this.InvokeOnUiThreadIfRequired(() => statusLabel.Text = args.Value);
        }

        private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
        {
            SetCanGoBack(args.CanGoBack);
            SetCanGoForward(args.CanGoForward);

            this.InvokeOnUiThreadIfRequired(() => SetIsLoading(!args.CanReload));
        }

        private void OnBrowserTitleChanged(object sender, TitleChangedEventArgs args)
        {
            this.InvokeOnUiThreadIfRequired(() => Text = args.Title);
        }

        private void OnBrowserAddressChanged(object sender, AddressChangedEventArgs args)
        {
            //this.InvokeOnUiThreadIfRequired(() => urlTextBox.Text = args.Address);
        }

        private void SetCanGoBack(bool canGoBack)
        {
            //this.InvokeOnUiThreadIfRequired(() => backButton.Enabled = canGoBack);
        }

        private void SetCanGoForward(bool canGoForward)
        {
            //this.InvokeOnUiThreadIfRequired(() => forwardButton.Enabled = canGoForward);
        }

        private void SetIsLoading(bool isLoading)
        {
            //goButton.Text = isLoading ? "Stop" : "Go";
            //goButton.Image = isLoading ? Properties.Resources.nav_plain_red : Properties.Resources.nav_plain_green;

            HandleToolStripLayout();
        }

        public void DisplayOutput(string output)
        {
            //this.InvokeOnUiThreadIfRequired(() => outputLabel.Text = output);
        }

        private void HandleToolStripLayout(object sender, LayoutEventArgs e)
        {
            HandleToolStripLayout();
        }

        private void HandleToolStripLayout()
        {
            //var width = toolStrip1.Width;
            //foreach (ToolStripItem item in toolStrip1.Items)
            //{
            //    if (item != urlTextBox)
            //    {
            //        width -= item.Width - item.Margin.Horizontal;
            //    }
            //}

            //urlTextBox.Width = Math.Max(0, width - urlTextBox.Margin.Horizontal - 18);
        }
        private void ExitButton_Click(object sender, EventArgs e)
        {
            Close();
            _browser.Dispose();
            Cef.Shutdown();
        }

        private void DevToolMenuItem_Click(object sender, EventArgs e)
        {
            _browser.ShowDevTools();
        }

        private void ExitMenuItem_Click(object sender, EventArgs e)
        {
            Close();
            _browser.Dispose();
            Cef.Shutdown();
        }

        private void PrintSettingMenuItem_Click(object sender, EventArgs e)
        {
            var printerSettingForm=new PrintSettingForm();
            printerSettingForm.Show();
        }

        private void MinimizedButton_Click(object sender, EventArgs e)
        {

            this.WindowState = FormWindowState.Minimized;
        }
        //实现需要开启与隐藏的高级功能菜单
        public void MenuShow()
        {
            //this.MenuStrip.Visible = true;
            this.DevToolMenuItem.Visible = true;
            this.PrintSettingMenuItem.Visible = true;
        }
        //实现需要开启与隐藏的高级功能菜单
        private void MenuHide()
        {
            //this.MenuStrip.Visible = false;
            this.DevToolMenuItem.Visible = false;
            this.PrintSettingMenuItem.Visible = false;
        }

        private void LogsMenuItem_Click(object sender, EventArgs e)
        {
            //todo 开打日志文件夹
            var dir = Directory.GetCurrentDirectory() + "\\logs";
            //System.Diagnostics.Process.Start("Explorer.exe", dir);
            System.Diagnostics.Process.Start(dir);
        }

        private void TestPrintMenuItem_Click(object sender, EventArgs e)
        {
            //var path = Directory.GetCurrentDirectory() + "\\EULA.pdf";
            Task.Factory.StartNew(() =>
            {
                var path =
                    "http://file3.data.weipan.cn/140823690/882483f400b7e1de465a4a6d3d1cf26a1566972d?ip=1534215337,183.48.46.103&ssig=eUo4spTP4X&Expires=1534215937&KID=sae,l30zoo1wmz&fn=%E6%96%87%E6%A1%A3.pdf&se_ip_debug=183.48.46.103&from=1221134";
                PrinterHelper.DownLoadAndPrint(path);
            });
        }
        
    }
}
